from flasgger import swag_from
from flask import g, request
from flask.views import MethodView

from app.advices.models import Advices
from app.extensions import json_response
from utils.base import login_require


class AdvicesView(MethodView):
    @login_require
    @swag_from("./apidocs/get_advices.yml")
    def get(self):
        user_id = g.user_id
        advices = Advices.get_advices()
        advice_list = []
        for advice in advices:
            advice_dict = advice.to_dict()
            can_delete = True if advice.user_id == user_id else False
            advice_dict["can_delete"] = int(can_delete)
            advice_list.append(advice_dict)
        return json_response(data=advice_list)

    @login_require
    @swag_from("./apidocs/add_advices.yml")
    def post(self):
        user_id = g.user_id
        body = request.json
        content = body.get("content")
        advice_dict = {"user_id": user_id, "content": content}
        res = Advices.create(**advice_dict)
        return json_response(data=res.to_dict())


class AdviceDeleteView(MethodView):
    @login_require
    @swag_from("./apidocs/delete_advice.yml")
    def delete(self, content_id):
        advice = Advices.delete_advice(g.user_id, content_id)
        return json_response(data=advice.to_dict())
